package com.kl.airticketserver.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kl.airticketserver.dto.LoginRequest;
import com.kl.airticketserver.dto.LoginResponse;
import com.kl.airticketserver.dto.Result;
import com.kl.airticketserver.entity.SysUser;
import com.kl.airticketserver.service.SysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/auth")
public class AuthController {
    
    private static final Logger log = LoggerFactory.getLogger(AuthController.class);
    
    @Autowired
    private SysUserService userService;
    
    @PostMapping("/login")
    public Result<LoginResponse> login(@Validated @RequestBody LoginRequest request) {
        log.info("用户登录请求: username={}", request.getUsername());
        
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.eq("username", request.getUsername());
        SysUser user = userService.getOne(wrapper);
        
        if (user == null || !user.getPassword().equals(request.getPassword())) {
            log.warn("登录失败: 用户名或密码错误, username={}", request.getUsername());
            return Result.error("用户名或密码错误");
        }
        
        if (user.getStatus() == 0) {
            log.warn("登录失败: 账户已被禁用, username={}", request.getUsername());
            return Result.error("账户已被禁用");
        }
        
        StpUtil.login(user.getId());
        
        LoginResponse response = new LoginResponse();
        response.setToken(StpUtil.getTokenValue());
        response.setUsername(user.getUsername());
        response.setNickname(user.getNickname());
        response.setAvatar(user.getAvatar());
        
        log.info("用户登录成功: username={}, userId={}", user.getUsername(), user.getId());
        return Result.success(response);
    }
    
    @PostMapping("/logout")
    public Result<Void> logout() {
        String userId = StpUtil.getLoginIdAsString();
        StpUtil.logout();
        log.info("用户登出: userId={}", userId);
        return Result.success(null);
    }
    
    @GetMapping("/userinfo")
    public Result<SysUser> getUserInfo() {
        String userId = StpUtil.getLoginIdAsString();
        log.debug("获取用户信息: userId={}", userId);
        SysUser user = userService.getById(userId);
        user.setPassword(null);
        return Result.success(user);
    }
}